//
//  GTGiftViewController.m
//  GiftTalk
//
//  Created by Wan on 16/3/22.
//  Copyright © 2016年 Wan. All rights reserved.
//

#import "GTGiftViewController.h"
#import "GTEditChannelView.h"
#import "GTChannelViewController.h"
#import "GTChoicenessViewController.h"
#import "GTSignViewController.h"
#import "GTSearchViewController.h"

/** 标签按钮最大可见数 */
static const CGFloat GTLabelButtonMaxVisibleCount = 5;
@interface GTGiftViewController() <UIScrollViewDelegate>

/** 标签scrollView */
@property (weak, nonatomic) IBOutlet UIScrollView *channelScrollView;
/** 内容 */
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
/** 编辑标签模式头视图 */
@property (weak, nonatomic) IBOutlet UIView *editChannelTitleView;
/** 切换频道提示Label */
@property (weak, nonatomic) IBOutlet UILabel *switchEditModeTipLabel;
/** 切换编辑模式按钮(排序或删除) */
@property (weak, nonatomic) IBOutlet UIButton *switchEditModeButton;


/** 底部索引控件 */
@property (weak, nonatomic) UIView *indicatorView;
/** 选中的按钮 */
@property (weak, nonatomic) UIButton *selectedButton;
/** 标签按钮 */
@property (strong, nonatomic) NSMutableArray *channelButtons;

/** 编辑频道内容 */
@property (weak, nonatomic) GTEditChannelView *editChannelView;

@end

@implementation GTGiftViewController

#pragma mark - 懒加载

- (NSMutableArray *)channelButtons
{
    if (!_channelButtons) {
        _channelButtons = [NSMutableArray array];
    }
    return _channelButtons;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1. 初始化导航栏
    [self setupNav];
    
    // 2. 初始化频道
    [self setupChildController];
    
    // 3. 初始化频道子标签
    [self setupChannelButtons];
    
    // 4. 初始化内容视图
    [self setupContentScrollView];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self setupChannelButtonsFrame];
}

/**
 *  设置底部的 scrollView 内容视图
 */
- (void)setupContentScrollView
{
    self.contentScrollView.delegate = self;
    self.contentScrollView.pagingEnabled = true;
    
    // 设置内容视图的内容尺寸
    self.contentScrollView.contentSize = CGSizeMake(self.childViewControllers.count * GTScreenW, 0);
    
    // 不要自动调整 ScrollView 的 Inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self scrollViewDidEndScrollingAnimation:self.contentScrollView];
}

/**
 *  初始化导航栏
 */
- (void)setupNav
{
    // 设置导航栏内容
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]];

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem initWithImage:@"feed_signin" target:self action:@selector(feedClick)];
    
    UIBarButtonItem *nightmode = [UIBarButtonItem initWithImage:@"icon_navigation_nightmode" target:self action:@selector(nightmode)];
    UIBarButtonItem *search = [UIBarButtonItem initWithImage:@"icon_navigation_search" target:self action:@selector(search)];
    NSArray *buttonArray = [[NSArray alloc] initWithObjects:search,nightmode, nil];
    
    self.navigationItem.rightBarButtonItems = buttonArray;
    
}

/**
 *  初始化子控制器
 */
- (void)setupChildController
{
    NSString *dataArrayName = @"items";
    
    // 内部的子标签
//    NSArray *titles = @[@"精选",@"数码",@"运动",@"娱乐",@"美食",@"礼物"];
    
    GTChoicenessViewController *choicenessVc = [[GTChoicenessViewController alloc] init];
    choicenessVc.cellBackgroundColor = [UIColor whiteColor];
    [self setupOneChildViewController:choicenessVc withTitle:@"精选" firstPageURLString:[self channelURLWithNumber:100] dataArrayName:dataArrayName];
    
//    GTChannelViewController *sm = [[GTChannelViewController alloc]

    [self setupOneChildViewController:[[GTChannelViewController alloc] init] withTitle:@"数码" firstPageURLString:[self channelURLWithNumber:121] dataArrayName:dataArrayName];
    [self setupOneChildViewController:[[GTChannelViewController alloc] init] withTitle:@"运动" firstPageURLString:[self channelURLWithNumber:123] dataArrayName:dataArrayName];
    [self setupOneChildViewController:[[GTChannelViewController alloc] init] withTitle:@"娱乐" firstPageURLString:[self channelURLWithNumber:120] dataArrayName:dataArrayName];
    [self setupOneChildViewController:[[GTChannelViewController alloc] init] withTitle:@"美食" firstPageURLString:[self channelURLWithNumber:118] dataArrayName:dataArrayName];
    [self setupOneChildViewController:[[GTChannelViewController alloc] init] withTitle:@"礼物" firstPageURLString:[self channelURLWithNumber:111] dataArrayName:dataArrayName];

}

- (void)setupOneChildViewController:(GTChannelViewController *)vc withTitle:(NSString *)title firstPageURLString:(NSString *)firstPageURLString dataArrayName:(NSString *)dataArrayName
{
    vc.title = title;
    vc.dataArrayName = dataArrayName;
    vc.firstPageURLString = firstPageURLString;
    [self addChildViewController:vc];
}

- (NSString *)channelURLWithNumber:(NSInteger)number
{
    NSMutableString *channelURL = [NSMutableString stringWithString:@"http://api.liwushuo.com/v1/channels/"];
    [channelURL appendFormat:@"%ld", number];
    [channelURL appendString:@"/items?limit=20&offset=0"];
    
    return channelURL;
}


/**
 *  初始化频道子标签
 */
- (void)setupChannelButtons
{
    // 底部指示器
    UIView *indicatorView = [[UIView alloc] init];
    indicatorView.backgroundColor = GTThemeColor;
    [self.channelScrollView addSubview:indicatorView];
    self.indicatorView = indicatorView;
    
    // 子标签按钮
    for (NSInteger i = 0; i < self.childViewControllers.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitleColor:GTThemeColor forState:UIControlStateNormal];
        [button setTitleColor:GTThemeColor forState:UIControlStateDisabled];
        [button addTarget:self action:@selector(channelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[self.childViewControllers[i] title] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [self.channelScrollView addSubview:button];
        [self.channelButtons addObject:button];
        // 设置默认选中按钮
        if (i == 0) {
            button.enabled = NO;
            self.selectedButton = button;
        }
    }
}

/**
 *  初始化标签位置
 */
- (void)setupChannelButtonsFrame
{
    // 设置索引控件坐标
    self.indicatorView.height = 2.5;
    self.indicatorView.y = self.channelScrollView.height - self.indicatorView.height;
    
    CGFloat buttonW = self.channelScrollView.width / GTLabelButtonMaxVisibleCount;
    CGFloat buttonH = self.channelScrollView.height;
    for (NSInteger i = 0; i < self.childViewControllers.count; i++) {
        // 设置标签按钮坐标
        UIButton *button = self.channelButtons[i];
        button.height = buttonH;
        button.width = buttonW;
        button.x = i * buttonW;
        
        if (i == 0 && self.selectedButton == button) {
            [button.titleLabel sizeToFit];
            self.indicatorView.width = button.titleLabel.width;
            self.indicatorView.centerX = button.centerX;
        }
    }
    
    // 因为上面被按钮覆盖了，所以不需要手动滑动，但是要求点击能让点击的频道标签居中
    self.channelScrollView.contentSize = CGSizeMake(self.channelButtons.count * buttonW, 0);
}


- (void)channelButtonClick:(UIButton *)button
{
    // 设置内容偏移，由内容来决频道标题
    CGFloat contentOffsetX = button.x / button.width * self.contentScrollView.width;;
    [self.contentScrollView setContentOffset:CGPointMake(contentOffsetX, 0) animated:YES];
    
    // 动画
//    [UIView animateWithDuration:0.25 animations:^{
//        self.indicatorView.width = button.titleLabel.width;
//        self.indicatorView.centerX = button.centerX;
//        
//        GTLog(@"%@",NSStringFromCGRect(self.indicatorView.frame));
//    }];
}

- (void)search
{
    GTSearchViewController *search = [[GTSearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}


- (void)nightmode
{
    GTLogFunc
}

/**
 *  签到
 */
- (void)feedClick
{
//    GTLog(@"点击 feed");
    GTSignViewController *signVc = [[GTSignViewController alloc] init];

    [self.navigationController pushViewController:signVc animated:YES];
}


- (void)loadViewControllerByIndex:(NSUInteger)index
{
    UIViewController *showVc = self.childViewControllers[index];
    // 如果控制器view已经被加载，就没有必要重新设置一次frame
    if ([showVc isViewLoaded]) return;
    
    CGFloat width = self.contentScrollView.width;
    CGFloat height = self.contentScrollView.height;
    CGFloat x = width * index;
    // 设置当前显示 view 的 frame
    showVc.view.frame = CGRectMake(x, 0, width, height);
    [self.contentScrollView addSubview:showVc.view];
}


- (void)setSelectedButtonItem:(UIButton *)selectedButton
{
    self.selectedButton.enabled = YES;
    self.selectedButton = selectedButton;
    self.selectedButton.enabled = NO;
    
    // 底部指示器动画
    [UIView animateWithDuration:0.25 animations:^{
        self.indicatorView.width = selectedButton.titleLabel.width;
        self.indicatorView.centerX = selectedButton.centerX;
    }];
}


#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    NSUInteger channelIndex = scrollView.contentOffset.x / scrollView.width;
    UIButton *channelButton = self.channelButtons[channelIndex];
    
    // 设置频道偏移量
    CGFloat channelOffsetX = channelButton.centerX - self.channelScrollView.width * 0.5;
    channelOffsetX = MIN(MAX(0, channelOffsetX), self.channelScrollView.contentSize.width - self.channelScrollView.width);
    [self.channelScrollView setContentOffset:CGPointMake(channelOffsetX, 0) animated:YES];
    
    [self setSelectedButtonItem:channelButton];
    [self loadViewControllerByIndex:channelIndex];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

@end
